import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ride_rex/article/comment.dart';
import 'package:ride_rex/main/video/video_page.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../person_detail/person_detail_logic.dart';
import '../../service/feed_service.dart';
import '../../sqlite/db_manager.dart';
import '../discover/discover_bean.dart';

class VideoLogic extends GetxController with CommonLife {
  final PageController pageController = PageController();

  List<FeedUserBean> list = [];
  List<GlobalKey> keyList = [];

  final FocusNode focusNode = FocusNode();
  final TextEditingController textEditingController = TextEditingController();

  FeedUserBean? videoBean;

  bool needRefresh = false;

  @override
  void onReady() {
    super.onReady();

    CommonObservable().addObserver(CommonLogic.keyListenerBlock, block);
    CommonObservable().addObserver(CommonLogic.keyListenerUnblock, unblock);
    CommonObservable().addObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().addObserver(CommonLogic.keyListenerUnfollow, unfollow);
    CommonObservable().addObserver(CommonLogic.keyListenerArticleLike, like);
    CommonObservable().addObserver(CommonLogic.keyListenerArticleCancelLike, cancelLike);
  }

  void onTapComment(FeedUserBean bean) {
    if (focusNode.hasFocus) {
      focusNode.unfocus();
      videoBean = null;
    } else {
      focusNode.requestFocus();
      videoBean = bean;
    }
  }

  void sendTextComment() async {
    if (videoBean == null) return;
    if (videoBean!.videoId.empty) return;
    if (Loading.predicate(() => textEditingController.text.trim().empty, 'Please enter your ideas')) return;
    CommentBean bean = CommentBean.text(text: textEditingController.text.trim());
    await DbManager.addComment(bean: bean, workId: videoBean!.videoId!);
    videoBean!.videoCommentList.add(bean);
    CommonOperate.nextFrameRefresh(() {
      VideoItemState? videoItemState = getVideoItemState();
      if (videoItemState == null) return;
      videoItemState.barrageWallController.send([BulletUtils.getBullets(bean, 0)]);
    });
    update();
    textEditingController.clear();
    focusNode.unfocus();
    videoBean = null;
  }

  ///获取item的state
  VideoItemState? getVideoItemState() {
    if (pageController.positions.isEmpty) return null;

    int index = pageController.page?.round() ?? 0;

    final itemState = keyList[index].currentState;

    if (itemState is VideoItemState) {
      return itemState;
    }
    return null;
  }

  void initData() async {
    Loading.show(clickMaskDismiss: false);

    ///要在数据库打开后执行
    await FeedService.instance.fetchData().whenComplete(() => Loading.dismiss());
    list = await DbManager.getLocalUserList();
    keyList = list.map((e) => GlobalKey()).toList();
    update();
    needRefresh = false;
  }

  ///视频点赞
  void like(key, [value]) {
    String videoName = value ?? '';
    for (FeedUserBean e in list) {
      if (e.localVideo.equals(videoName)) {
        e.isVideoLike = true;
      }
    }
    update();
  }

  ///视频取消点赞
  void cancelLike(key, [value]) {
    String videoName = value ?? '';
    for (FeedUserBean e in list) {
      if (e.localVideo.equals(videoName)) {
        e.isVideoLike = false;
      }
    }
    update();
  }

  void block(key, [value]) {
    String userId = value ?? '';
    if (userId.empty) return;

    ///要删除的下标列表
    List<int> indexesToRemove = [];

    ///从list中删除并记录被删除的videoId
    for (FeedUserBean e in list) {
      if (e.userId.equals(userId)) {
        indexesToRemove.add(list.indexOf(e));
      }
    }

    list.removeWhere((element) => element.userId.equals(userId));

    ///将要删除的下标按降序排列
    indexesToRemove.sort((a, b) => b.compareTo(a));

    ///从keyList中删除
    for (int index in indexesToRemove) {
      if (index < keyList.length) {
        keyList.removeAt(index);
      }
    }

    if (pageController.positions.isEmpty) return;

    update();
  }

  void unblock(key, [value]) async {
    needRefresh = true;
  }

  void follow(key, [value]) {
    String userId = value ?? '';
    for (var value1 in list) {
      if (value1.userId.equals(userId)) {
        value1.isFriend = true;
      }
    }
    update();
  }

  void unfollow(key, [value]) {
    String userId = value ?? '';
    for (var value1 in list) {
      if (value1.userId.equals(userId)) {
        value1.isFriend = false;
      }
    }
    update();
  }

  @override
  void onClose() {
    super.onClose();
    pageController.dispose();
    CommonObservable().removeObserver(CommonLogic.keyListenerBlock, block);
    CommonObservable().removeObserver(CommonLogic.keyListenerUnblock, unblock);
    CommonObservable().removeObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().removeObserver(CommonLogic.keyListenerUnfollow, unfollow);
    CommonObservable().removeObserver(CommonLogic.keyListenerArticleLike, like);
    CommonObservable().removeObserver(CommonLogic.keyListenerArticleCancelLike, cancelLike);
  }

  @override
  void pageBack() {
    super.pageBack();

    if (needRefresh) {
      initData();
    } else {
      VideoItemState? videoItemState = getVideoItemState();
      if (videoItemState == null) return;
      videoItemState.play();
    }
  }

  @override
  void pageLeave() {
    super.pageLeave();

    VideoItemState? videoItemState = getVideoItemState();
    if (videoItemState == null) return;
    videoItemState.pause();
  }
}
